package com.et.u1.util.widget;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffColorFilter;
import android.graphics.drawable.BitmapDrawable;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.ImageView;

import com.et.u1.R;


public class HeartView extends androidx.appcompat.widget.AppCompatImageView {

    private static final Paint sPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG);
    private static Bitmap sHeart;
    private static final Canvas sCanvas = new Canvas();

    public HeartView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public HeartView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public HeartView(Context context, int res) {
        super(context);
        Bitmap heart = createHeart(res);
        setImageDrawable(new BitmapDrawable(getResources(), heart));
    }


    public Bitmap createHeart(int res) {
        sHeart = BitmapFactory.decodeResource(getResources(), res);
        Bitmap heart = sHeart;
        Bitmap bm = createBitmapSafely(heart.getWidth(), heart.getHeight());
        if (bm == null) {
            return null;
        }
        Canvas canvas = sCanvas;
        canvas.setBitmap(bm);
        canvas.drawBitmap(heart, 0, 0, sPaint);
        return bm;
    }

    private static Bitmap createBitmapSafely(int width, int height) {
        try {
            return Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        } catch (OutOfMemoryError error) {
            error.printStackTrace();
        }
        return null;
    }

}
